# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2022-11-23 18:06:00
@describe:
"""
import json

from app.db.db_api import ToolsSql
from requests.adapters import HTTPAdapter
from app.common.common_func import Common
from app.log.ulog import logger_

import requests
import uuid


def off_repay(env: str, asset_id: str, period: str, repay_time: str) -> dict:
	# 获取进件与资产信息
	asset_project_detail = ToolsSql.select_project_and_asset(env, asset_id)

	s = requests.session()
	# 设置请求重试次数
	s.mount("http://", HTTPAdapter(max_retries=3))
	s.mount("https://", HTTPAdapter(max_retries=3))
	urls = Common.get_yaml_data("config", "url.yaml")
	# 设置请求头
	headers = {}
	_uuid = str(uuid.uuid4())
	trace_id = _uuid.split("-")[-2] + _uuid.split("-")[-1]
	headers["X-B3-TraceId"] = trace_id
	headers["X-B3-SpanId"] = trace_id
	headers["X-TBC-SOURCE"] = asset_project_detail["project"]["channel"]
	headers["Content-Type"] = "application/json"
	if asset_project_detail["project"]["channel"] == "ylkj":
		source_code = f"tbc_zhtb_gred"
	else:
		source_code = f"tbc_zhtb_{asset_project_detail['project']['channel']}"

	# 查询还款计划
	kwg = {
		"channel": asset_project_detail["project"]["channel"],
		"sourceCode": source_code.split("_")[-1],
		"transactionId": asset_project_detail["transaction_id"],
		"projectId": asset_project_detail["project_id"]
	}

	logger_.info(f"""请求头:{headers}""")
	logger_.info(f"""请求参数:{kwg}""")

	rep = s.post(
		headers=headers,
		data=json.dumps(kwg, ensure_ascii=False).encode("utf-8"),
		url=urls["url"][env] + "/api/v1/busi/project/queryRepaymentPlan"
	).text

	logger_.info(f"""响应结果:{rep}""")
	repayment_plan = json.loads(rep)['content']['repaymentPlanList']

	kwg2 = {
		"channel": "rmkj",
		"sourceCode": "rmkj",
		"projectId": "488921939",
		"transactionId": "9123904034",
		"sourceProjectId": "818239",
		"sourcePlanId": "839193",
		"sourceRepaymentId": "1823993",
		"assetPlanOwner": 0,
		"repayType": 1,
		"payTime": "2019-10-22",
		"period": 1,
		"successAmount": 3333.33,
		"overdueStatus": 0,
		"paymentFlowSource": 3,
		"repaymentDetailList": [
			{
				"sourceRepaymentDetailId": "8499103",
				"payAmount": 3333.00,
				"planCategory": 1
			},
			{
				"sourceRepaymentDetailId": "8499103",
				"payAmount": 0.33,
				"planCategory": 2
			}
		]
	}

	kwg2.update(
		{
			"channel": asset_project_detail["project"]["channel"],
			"sourceCode": source_code.split("_")[-1],
			"projectId": asset_project_detail["project_id"],
			"transactionId": asset_project_detail["transaction_id"],
			"sourceProjectId": asset_project_detail["source_project_id"],
			"sourcePlanId": Common.get_random("repaymentPlanId"),
			"sourceRepaymentId": Common.get_random("repaymentPlanId"),
			"period": period,
			"payTime": repay_time
		}
	)

	success_amount = 0.00
	repayment_detail_list = []
	# 组装本金利息流水
	for i in repayment_plan:
		if (str(i['period']) == kwg2["period"]) and (i.get("repaymentStatus", 1) == 1):
			plan_detail = {
				"sourceRepaymentDetailId": Common.get_random("transactionId"),
				"payAmount": i['restAmount'] if i.get("restAmount", None) is not None else i["amount"],
				"planCategory": i['repaymentPlanType']
			}
			success_amount = round(success_amount + float(plan_detail.get("payAmount")), 2)
			repayment_detail_list.append(plan_detail)

	kwg2["successAmount"] = success_amount
	kwg2["repaymentDetailList"] = repayment_detail_list

	_uuid = str(uuid.uuid4())
	trace_id = _uuid.split("-")[-2] + _uuid.split("-")[-1]
	headers["X-B3-TraceId"] = trace_id
	headers["X-B3-SpanId"] = trace_id

	logger_.info(f"""还款请求头:{headers}""")
	logger_.info(f"""还款申请参数:{kwg2}""")

	rep = s.post(
		headers=headers,
		data=json.dumps(kwg2, ensure_ascii=False).encode("utf-8"),
		url=urls["url"][env] + "/api/v1/busi/offline/repay"
	).text

	logger_.info(f"""还款申请结果:{rep}""")

	return {"headers": headers, "request": kwg2, "response": rep}
